package com.daiyang.javabasics.demo1;

import java.util.ArrayList;
import java.util.List;

public class Test2 {
    public static void main(String[] args) {
        findAnagrams("abab","ab");
    }
    public static List<Integer> findAnagrams(String s, String p) {
        List<Integer> list =new ArrayList<>();
        int [] hashs=new int [26];
        int [] hashp =new int [26];
        int sl=s.length();
        int pl=p.length();
        char [] ss=s.toCharArray();
        char [] pp=p.toCharArray();
        if(sl>pl) {
            for(int i=0;i<pl;i++) {
                int in=pp[i] - 'a';
                hashp[in]++;
            }
            int left=0;
            int right=0;
            while(right<ss.length) {
                while(right-left<=pl-1) {
                    int in=ss[right]-'a';
                    hashs[in]++;
                    right++;
                }
                if(cheack(hashp,hashs)) {
                    list.add(left);
                }
                hashs[ss[left]-'a']--;
                left++;
                hashs[ss[right]-'a']++;
                right++;
            }
            return list;

        } else {
            for(int i=0;i<sl;i++) {
                int in=ss[i] - 'a';
                hashp[in]++;
            }
            int left=0;
            int right=0;
            while(right<pp.length) {
                while(right-left<=sl-1) {
                    int in=pp[right]-'a';
                    hashs[in]++;
                    right++;
                }
                if(cheack(hashp,hashs)) {
                    list.add(left);
                }
                hashs[pp[left]-'a']--;
                left++;
                hashs[pp[right]-'a']++;
                right++;
            }
            return list;
        }
    }
    public static boolean cheack(int [] hashp,int [] hashs) {
        for(int i=0;i<26;i++) {
            if(hashp[i]!=hashs[i]) return false;
        }
        return true;
    }
}
